package com.xl.rentkeeper.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.xl.fuse.protos.viewroom.ViewOrder;
import com.xl.fuse.protos.viewroom.ViewOrderStatus;
import com.xl.rentkeeper.App;
import com.xl.rentkeeper.R;
import com.xl.rentkeeper.act.jiedan.ProcessOrderDetailsAct;
import com.xl.rentkeeper.adapter.OrderAdapter;
import com.xl.rentkeeper.business.OrderLogic;
import com.xl.rentkeeper.entity.Order;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.util.DialogUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2015/7/21.
 */
public class PendingFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener,Handler.Callback,DialogUtil.DialogCallback {
    public ListView mLVOrder;
    public OrderAdapter mAdapter;
    private List<Order> mList = new ArrayList<>();
    private Dialog mDialog;
    private SwipeRefreshLayout mSRLList;
    private Handler mHandler = new Handler(this);
    private TextView mTVNodata;
    public static String reqContext ="pendingfragment";

    @Override
    protected View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_orderlist, null);
        mLVOrder = (ListView) view.findViewById(R.id.lv_order);
        mTVNodata = (TextView) view.findViewById(R.id.tv_nodata);
//        mAdapter = new OrderAdapter(getActivity().getLayoutInflater(),mList);
        mAdapter = new OrderAdapter(mActivity, getActivity().getLayoutInflater(), mList);
        mAdapter.setDialogCallback(this);
        mLVOrder.setAdapter(mAdapter);
        mLVOrder.setOnItemClickListener(this);

        mSRLList = (SwipeRefreshLayout) view.findViewById(R.id.id_swipe_ly);
        mSRLList.setOnRefreshListener(this);
        //给listview设置headerview
        return view;
    }


    @Override
    protected void initData() {
        reloadData();
        if (mList.size() == 0) {
            OrderLogic.getInstance().queryOrder(0, OrderLogic.CMD_ORDER_NOT_RECEIVE_AND_CMD_ORDER_IS_RECEIVE, 0, 0);
        }

    }


    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        if (mList.get(position).viewOrder.status == ViewOrderStatus.ORDER_NOT_RECEIVE.getValue()) {
            Intent intent = new Intent(mActivity, ProcessOrderDetailsAct.class);
            intent.putExtra("msg", mList.get(position));
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
           // recevierOrder(mList.get(position));
        } else {
            Intent intent = new Intent(mActivity, ProcessOrderDetailsAct.class);
            intent.putExtra("msg", mList.get(position));
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
        }
    }

    private void recevierOrder(Order order) {
        mDialog = DialogUtil.showProgressDialog(mActivity, R.string.loading);
        OrderLogic.getInstance().stewardOrder(order.viewOrder.id, reqContext);//
    }

    @Override
    public void onRefresh() {
        OrderLogic.getInstance().queryOrder(0, OrderLogic.CMD_ORDER_NOT_RECEIVE_AND_CMD_ORDER_IS_RECEIVE, 0, 0);
    }

    public String[] monitorEvents() {
        return new String[]{OrderLogic.CMD_ORDER_NOT_RECEIVE_AND_CMD_ORDER_IS_RECEIVE, PMS_LOGIC_StewardOrder, OrderLogic.CMD_PROCESSING_ORDER_STATUS_UPDATE};
    }

    @Override
    public void onEvent(String event, boolean ret,String errInfo,Object[] data) {
        if (event.equals(OrderLogic.CMD_ORDER_NOT_RECEIVE_AND_CMD_ORDER_IS_RECEIVE)) {
            mSRLList.setRefreshing(false);
            reloadData();
        } else if (event.equals(PMS_LOGIC_StewardOrder)) {
            if(!reqContext.equals(data[2])){
                return;
            }
            mSRLList.setRefreshing(false);
            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
            if (ret) {
                if(data!=null && data[0]!=null){
                    final ViewOrder returnOrder = (ViewOrder)data[0];
                    final String msg = "恭喜!你已成功接单,是否立即与客户: "+returnOrder.name+"("+returnOrder.phone+") 联系?";
                    DialogUtil.showMsgInfoDialog(mActivity, new DialogUtil.DismissClickListener() {
                        @Override
                        public void okClick() {
                            Uri uri = Uri.parse("tel:" + returnOrder.phone);
                            Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                            mActivity.startActivity(intent);
                        }

                        @Override
                        public void cancelClick() {

                        }
                    }, msg, "成功接单","立即联系","稍后联系");
                }else{

                }
            }else{
                App.showToast(errInfo);
            }
        } else if (event.equals(OrderLogic.CMD_PROCESSING_ORDER_STATUS_UPDATE)) {
            reloadData();
        }
    }

    private void reloadData() {
        List<Order> notReceiveList = OrderLogic.getInstance().getListByStatus(ViewOrderStatus.ORDER_NOT_RECEIVE.getValue());
        List<Order> receiveList = OrderLogic.getInstance().getListByStatus(ViewOrderStatus.ORDER_IS_RECEIVE.getValue());

        Iterator<Order> i = notReceiveList.iterator();
        while (i.hasNext()) {
            Order r = i.next(); // must be called before you can call i.remove()
            long time = System.currentTimeMillis() - r.createTime;
            if(time<0){
                r.timeoutLength ="10:00";
                continue;
            }
            if(time>10*60*1000){
                r.timeoutLength = "超时10分钟";
//                i.remove();
//                OrderLogic.getInstance().removeOrder(r.id);
            }else{
                long remainTime = 600-(time/1000);
                long m = remainTime/60;
                long s = remainTime%60;
                String mm ="";
                String ss ="";
                if(m<10){
                    mm="0"+m;
                }else{
                    mm =""+m;
                }
                if(s<10){
                    ss="0"+s;
                }else{
                    ss =""+s;
                }
                r.timeoutLength = mm+":"+ss;
            }
        }

        for(Order r : receiveList){
            long time = System.currentTimeMillis() - r.orderStewardTime;
            if(time<0){
                r.timeoutLength ="10:00";
                continue;
            }
            if(time>10*60*1000){
                r.timeoutLength = "超时10分钟";
            }else{
                long remainTime = 600-(time/1000);
                long m = remainTime/60;
                long s = remainTime%60;
                if(m>0){
                    r.timeoutLength =""+m+":"+s;
                }else{
                    r.timeoutLength = ""+s;
                }
            }
        }
        mList.clear();
        if (notReceiveList.size() != 0) {
            mList.addAll(notReceiveList);
        }
        if (receiveList.size() != 0) {
            mList.addAll(receiveList);
        }
//        ((MainActivity)mActivity).setReceiveMsgCount();
        refreshView();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        QLog.d(this, "setVisible " + isVisibleToUser);
    }

    private void refreshView() {
        if(mList.size()==0){
            mTVNodata.setVisibility(View.VISIBLE);
        }else{
            mTVNodata.setVisibility(View.INVISIBLE);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.what ==1){
            QLog.d(this,"onFresh");
            reloadData();
            mHandler.sendEmptyMessageDelayed(1,1000);
        }
        return false;
    }

    @Override
    public void onConfirm(Object o) {
        Order order = (Order)o;
        recevierOrder(order);
    }

    public void refresh(boolean fresh) {
        if (fresh) {
            mHandler.removeMessages(1);
            mHandler.sendEmptyMessageDelayed(1, 1000);
        } else {
            mHandler.removeMessages(1);
        }
    }

}
